import cv2
import numpy as np



# 读取图片
img = cv2.imread('11.jpg',1)
h,w = img.shape[:2]
print("图片的原像素为:",h,w)

#灰度处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 二值化
# binary = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
# ret,binary = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
ret,binary = cv2.threshold(gray,70,255,cv2.THRESH_BINARY)
# ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_TRIANGLE)
# 中值滤波
median_filtered = cv2.medianBlur(binary, 25)

# 开运算操作
kernel = np.ones((5, 5), np.uint8)
opening = cv2.morphologyEx(median_filtered, cv2.MORPH_OPEN, kernel, iterations=3)  # iterations进行3次操作

# 轮廓拟合
contours, hierarchy = cv2.findContours(opening, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[1]  # 得到物体的轮廓
# rect = cv2.minAreaRect(cnt)
# box = cv2.boxPoints(rect)
# box = np.int0(box)
cv2.drawContours(img, cnt, -1, (0, 0, 255), 3)  # 画矩形框

# 图像轮廓及中心点坐标
M = cv2.moments(cnt)  # 计算第一条轮廓的各阶矩,字典形式
center_x = int(M['m10'] / M['m00'])
center_y = int(M['m01'] / M['m00'])
print('center_x:', center_x)
print('center_y:', center_y)
cv2.circle(img, (center_x, center_y), 7, 128, -1)  # 绘制中心点
str1 = '(' + str(center_x) + ',' + str(center_y) + ')'  # 把坐标转化为字符串
cv2.putText(img, str1, (center_x - 50, center_y + 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 0), 2,
            cv2.LINE_AA)  # 绘制坐标点位

resized_src = cv2.resize(img, (800,600))  # 缩放图像至新的尺寸
cv2.imshow('resized show', resized_src)
cv2.waitKey(0)
cv2.destroyAllWindows()


